package com.lt.androidsocketserver.http;



import com.lt.androidsocketserver.ThreadPoolUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author LiuTong
 */
public class HttpServer {
    private final int PORT = 12345;
    private static final String TAG = HttpServer.class.getSimpleName();
    private volatile boolean isRunning = false;
    private HttpCallback httpCallback;
    private ServerSocket serviceSocket;

    public HttpServer(HttpCallback httpCallback){
        this.httpCallback = httpCallback;
    }
    /****
     * 开启服务
     */
    public void startServer(){
        if(isRunning){
            closeHttpServer();
            return;
        }
        isRunning =true;
        try {
            serviceSocket = new ServerSocket(PORT);

            System.out.println("创建成功\n"+"IP:"+serviceSocket.getInetAddress().getCanonicalHostName());

            while (isRunning){
                Socket socket = serviceSocket.accept();
                System.out.println("Socket Name :" +socket.getInetAddress().getHostAddress());
                ThreadPoolUtils.getInstance().runTask(new HttpThread(socket,httpCallback));
            }

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

    }
    public boolean isHttpRunning(){
        return isRunning;
    }

    public void closeHttpServer(){
        if(serviceSocket != null && !serviceSocket.isClosed()){
            isRunning = false;
            try {
                serviceSocket.close();

            } catch (IOException ioException) {
                isRunning = true;
                ioException.printStackTrace();
            }

            if(serviceSocket == null || serviceSocket.isClosed()){
                System.out.println("socketServer 关闭成功");
            }
        }
    }
}
